import moment from 'moment';
import { notification, message } from 'antd';
import {
  queryRule,
  queryVideoCode,
  queryMatTime,
  removeRule,
  addRule,
  updateRule,
  publishRule,
  uploadRule,
  auditMat,
  uploadTraffic,
  uploadWeather,
  uploadEditRule,
} from '../services/api';
import update from 'immutability-helper';

function method(str, a, b) {
  let type = 'string';
  if (str === 'createTime') {
    type = 'date';
  } else if (str === 'matId') {
    type = 'num';
  }
  switch (type) {
    case 'num': // 数字排序
      return a - b;
    case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
      return moment(a).unix() - moment(b).unix();
    default:
      // 字符串排序
      return a.localeCompare(b);
  }
}
export default {
  namespace: 'rule',

  state: {
    list: [],
    pagination: {},
    VideoCode: [],
    MatTime: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryRule, payload);
      //console.log('rule fetch', payload);
      let dataSource = response.adMats;
      if (payload) {
        if (payload.sorter) {
          const s = payload.sorter.split('_');

          if (s[1] === 'descend') {
            dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
          } else {
            dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
          }
          // dataSource = dataSource.sort((prev, next) => {
          //   if (s[1] === 'descend') {
          //     return next[s[0]] - prev[s[0]];
          //   }
          //   return prev[s[0]] - next[s[0]];
          // });
        }

        let pageSize = 10;
        if (payload.pageSize) {
          pageSize = payload.pageSize * 1;
        }

        const result = {
          list: dataSource,
          pagination: {
            total: response.pageInfo.pageTotal,
            pageSize,
            current: parseInt(payload.page, 10) || 1,
          },
        };
        yield put({
          type: 'save',
          payload: result,
        });
      }
    },
    *fetchVideoCode({ payload }, { call, put }) {
      const response = yield call(queryVideoCode, payload);
      //console.log('rule fetch', payload);
      const result = response.videoFormatCodes;
      yield put({
        type: 'saveVideoCode',
        payload: result,
      });
    },
    *fetchMatTime({ payload }, { call, put }) {
      const response = yield call(queryMatTime, payload);
      //console.log('rule fetch', payload);
      const result = response.tiSlotCodes;
      yield put({
        type: 'saveMatTime',
        payload: result,
      });
    },

    *uploadRule({ payload, callback }, { call, put }) {
      const response = yield call(uploadRule, payload);
      if (response?.result?.code === 2001) {
        message.error('上传素材出错，请检查');
      } else {
        yield put({
          type: 'uploadMat',
          payload: response.uploadMatProgAutoEditPub,
        });
        if (callback) callback();
      }
    },
    *uploadWeather({ payload, callback }, { call, put }) {
      const response = yield call(uploadWeather, payload);
      if (response?.result?.code === 2001) {
        message.error('上传素材出错，请检查');
      } else {
        yield put({
          type: 'uploadMat',
          payload: response.weatherDet,
        });
        if (callback) callback();
      }
    },
    *uploadTraffic({ payload, callback }, { call, put }) {
      const response = yield call(uploadTraffic, payload);
      if (response?.result?.code === 2001) {
        message.error('上传素材出错，请检查');
      } else {
        yield put({
          type: 'uploadMat',
          payload: response.trafficInfoMat,
        });
        if (callback) callback();
      }
    },
    *uploadEditRule({ payload, callback }, { call, put }) {
      const response = yield call(uploadEditRule, payload);
      if (response?.result?.code === 2001) {
        message.error('上传素材出错，请检查');
      } else {
        yield put({
          type: 'editMat',
          payload: response.editAdMat,
        });
        if (callback) callback();
      }
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(addRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const { matId } = payload;
      //console.log('matId', matId);
      const newpayload = { matIds: matId.join(',') };
      const response = yield call(removeRule, newpayload);
      // const list = state.list.filter(item => matId.indexOf(item.matId) === -1);
      yield put({
        type: 'removeRule',
        payload: { matId },
      });
      if (callback) callback();
    },
    *auditMat({ payload, callback }, { call, put }) {
      const response = yield call(auditMat, payload);
      if (response?.result?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateRule, payload);

      if (response.result.code === 1000) {
        notification.success({
          message: `更新成功`,
        });
      }
    },
    *publish({ payload, callback }, { call, put }) {
      const response = yield call(publishRule, payload);
      if (response.result.code === 1000) {
        notification.success({
          message: `发布成功`,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload.list ? action.payload.list : [],
        pagination: action.payload.pagination,
      };
    },
    saveVideoCode(state, action) {
      return {
        ...state,
        VideoCode: action.payload,
      };
    },
    saveMatTime(state, action) {
      return {
        ...state,
        MatTime: action.payload,
      };
    },
    removeRule(state, action) {
      const newlist = state.list.filter(item => action.payload.matId.indexOf(item.matId) === -1);
      return {
        ...state,
        list: newlist,
      };
    },
    uploadMat(state, action) {
      const newState = update(state, {
        list: {
          $splice: [[0, 0, action.payload]],
        },
      });
      return newState;
    },
    editMat(state, action) {
      const index = state.list.findIndex(item => item.matId === action.payload.matId);
      const newitem = { ...action.payload, createTime: action.payload.updateTime };
      const newState = update(state, {
        list: {
          $splice: [[index, 1, newitem]],
        },
      });
      return newState;
    },
  },
};
